package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import static com.atguigu.spzx.manager.constants.RedisConstants.LOGIN_USERINFO_KEY;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求方式
        String method = request.getMethod();

        // 如果请求方式是options 预检请求，直接放行
        if ("OPTIONS".equals(method)) {
            return true;
        }

        // 2.从请求头获取token
        String token = request.getHeader("token");
        String bearer = token.replace("Bearer ", "");

        // 3.如果token为空，返回错误提示
        if (StringUtils.isBlank(token)) {
            responseNoLoginInfo(response);
            return false;
        }

        // 4.如果token不为空，拿着token查询redis
        String userInfo = stringRedisTemplate.opsForValue().get(LOGIN_USERINFO_KEY + bearer);

        // 5.如果redis查询不到数据，返回错误提示
        if (StringUtils.isBlank(userInfo)) {
            responseNoLoginInfo(response);
            return false;
        }

        // 6.如果redis查询到用户信息，把用户信息放到ThreadLocal
        AuthContextUtil.set(JSON.parseObject(userInfo, SysUser.class));

        // 7.把redis用户信息数据更新过期时间
        stringRedisTemplate.expire(LOGIN_USERINFO_KEY+ token, 30, TimeUnit.MINUTES);

        // 8.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // ThreadLocal删除
        AuthContextUtil.remove();
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}
